//
//  CZUserAccountViewModel.swift
//  weibo10
//
//  Created by apple on 16/5/14.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {

    //单例
    
    static let sharedInstance:CZUserAccountViewModel = CZUserAccountViewModel()
    //账号归档和解档的路径
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    //账号，全局只要拿到单例久可以访问，别人在任何地方都可以
    var userAccount : CZUserAccount?
    
    //用户是否登录
    var isUserLogin: Bool
        {
    get {
        //账号不等于nil就表示登录成功了
        return userAccount != nil
        }
    }
    
  private  override init() {
        super.init()
        //单例创建的时候就会加载沙盒里的账号，赋值userAccount给，只需要加载一次
       userAccount = loadUserAccount()
       
    }
    
    //发送POST请求获取AccessToken
    func loadAccessToken(code: String,callback: (error: NSError?) -> ())
    {
    //路径
        let urlString = "oauth2/access_token"
        //参数
        let parameters = [
            "client_id":client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri]
    
        // 如果已经授权成功消息在授权的时候不会再看到这个界面,相当于新浪会自动帮我们点击授权按钮,
        // 如果还想自己来收取需要去网站上面取消授权
        
        CZNetworkTool.sharedInstance.request(RequestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
             CZPrint(items: "获取AccessToken成功: \(responseObject)")
            
            // 判断返回的数据是否能够转成字典
            if let result = responseObject as? [String: AnyObject] {
                // 字典转模型
                let userAccount = CZUserAccount(dict: result)
                CZPrint(items: "userAccount: \(userAccount)")
                
                CZPrint(items: "userAccountPath: \(self.userAccountPath)")
                
                // 将账号赋值给属性
                self.userAccount = userAccount
                
                
                
                // 调用归档的方法,将模型归档到沙盒里面
                // 让userAccount对象保存到self.userAccountPath这个路径
               
                self.saveUserAccount()
                
                
                // 告诉控制器,模型保存完成了
                callback(error: nil)
            } else {
                CZPrint(items: "返回数据转字典失败了")
            }
            
            }, failure:
            {
            (task ,error) -> Void in
                callback(error: error )
            
            })
    }
    
   //将账号保存到沙盒中
    private func saveUserAccount()
    {
        
        
    if let account = userAccount
    {
        NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        
        }
    }
    
    
    
    // 解档账号
 private  func loadUserAccount() -> CZUserAccount? {
        // 解档对象
        // 从self.userAccountPath文件里面加载账号
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount {
           
            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
                // 没有过期
                CZPrint(items: "没有过期")
                return userAccount
            } else {
                return nil
            }
        } else {
            // 没有加载出账号
            return nil
        }
    }

//  MARK: - 获取用户名称和头像
    func loadUserInfo(loadUserInfoCallback: () -> ())
    {
    //guard和if相反 没有值走里面 没值直接走外面 不需再进行判断
        
    guard let access_token = userAccount?.access_token else
    {
        CZPrint(items: "access_token没有值")
        return
        }
    
        guard let uid = userAccount?.uid else
        {
        CZPrint(items: "uid没有值")
            return
        }
        let urlString = "2/users/show.json"
            
            //参数 是数组
        let parameters = [
            "access_token": access_token,
            "uid": uid]
    
            //发送请求
            CZNetworkTool.sharedInstance.request(RequestMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responseObject) -> Void in
                
                if let result = responseObject as? [String : AnyObject]
                {
                //只需要用户的名称和头像
                    let screen_name = result["screen_name"] as? String
                    
                    let avatar_large = result["avatar_large"] as? String
                    
                    //赋值到当前账号的模型中
                    self.userAccount?.screen_name = screen_name
                    self.userAccount?.avatar_large = avatar_large
                    
                    //将userAccount保存到沙盒中
                    self.saveUserAccount()
                    
                    //让欢迎界面显示信息 通过闭包回调
                    loadUserInfoCallback()
                
                }
                })  { (_, error) -> Void in
                    CZPrint(items: "2/users/show.json获取用户信息出错了: \(error)")
            }
        
        }
        
    }
  



